package com.lixueju.security.box.validate.code;

import com.lixueju.security.box.core.dto.SecurityBoxUtils;
import com.lixueju.security.box.core.properties.SecurityBoxConstants;
import com.lixueju.security.box.core.properties.SecurityBoxProperties;
import com.lixueju.security.box.core.support.SecurityBoxHttpServletRequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 验证码校验过滤器
 * </p>
 *
 * @author lixueju
 * @since 2019-08-16
 */
@Component
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    // 系统配置信息
    @Autowired
    private SecurityBoxProperties securityBoxProperties;

    // 系统中的校验码处理器
    @Autowired
    private ValidateCodeProcessorHolder validateCodeProcessorHolder;

    // 存放所有需要校验验证码的url
    private Map<String, ValidateCodeType> urlMap = new HashMap<>();

    // spring 工具类：路径匹配规则
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Autowired
    private SecurityBoxUtils securityBoxUtils;

    /**
     * 初始化要拦截的url配置信息
     */
    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();

        //urlMap.put(SecurityBoxConstants.DEFAULT_LOGIN_PROCESSING_URL, ValidateCodeType.IMAGE);
        addUrlToMap(securityBoxProperties.getCode().getImage().getUrl(), ValidateCodeType.IMAGE);

        urlMap.put(SecurityBoxConstants.DEFAULT_LOGIN_PROCESSING_URL_SMS, ValidateCodeType.SMS);
        urlMap.put(SecurityBoxConstants.DEFAULT_URL_BIND_MOBILE, ValidateCodeType.SMS);
        urlMap.put(SecurityBoxConstants.DEFAULT_URL_UPPASSWORD_BY_MOBILE, ValidateCodeType.SMS);
        addUrlToMap(securityBoxProperties.getCode().getSms().getUrl(), ValidateCodeType.SMS);
    }

    /**
     * 讲系统中配置的需要校验验证码的URL根据校验的类型放入map
     *
     * @param urlString
     * @param type
     */
    protected void addUrlToMap(String urlString, ValidateCodeType type) {
        if (StringUtils.isNotBlank(urlString)) {
            String[] urls = StringUtils.splitByWholeSeparatorPreserveAllTokens(urlString, ";");
            for (String url : urls) {
                urlMap.put(url, type);
            }
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(
     * javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        ValidateCodeType type = getValidateCodeType(request);
        if (type != null) {
            SecurityBoxHttpServletRequestWrapper requestWrapper = new SecurityBoxHttpServletRequestWrapper(request);
            logger.info("校验请求(" + request.getRequestURI() + ")中的验证码,验证码类型" + type);
            try {
                validateCodeProcessorHolder.findValidateCodeProcessor(type)
                        .validate(new ServletWebRequest(requestWrapper, response));
                logger.info("验证码校验通过");
            } catch (ValidateCodeException exception) {
                securityBoxUtils.writeFail(response, exception.getMessage());
                return;
            }
            chain.doFilter(requestWrapper, response);
        }else{
            chain.doFilter(request, response);
        }
    }

    /**
     * 获取校验码的类型，如果当前请求不需要校验，则返回null
     *
     * @param request
     * @return
     */
    private ValidateCodeType getValidateCodeType(HttpServletRequest request) {
        ValidateCodeType result = null;
        if (!StringUtils.equalsIgnoreCase(request.getMethod(), "get")) {
            Set<String> urls = urlMap.keySet();
            for (String url : urls) {
                if (pathMatcher.match(url, request.getRequestURI())) {
                    result = urlMap.get(url);
                }
            }
        }
        return result;
    }
}
